<template>
  <div class="update-avator">
    <img :src="photo" class="img" ref="image" />

    <footer class="toolbar">
      <span @click="$parent.$parent.isShowAvator = false">取消</span>
      <span @click="uploadAvator">完成</span>
    </footer>
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { uploadAvator } from '@/api'
export default {
  props: {
    photo: {
      type: String,
      required: true
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: 'none',
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      })
    },
    //? 上传头像
    uploadAvator() {
      //? 1. 获取截取后的图片的file对象
      this.myCropper.getCroppedCanvas().toBlob(async (blob) => {
        this.$toast.loading({
          message: '正在上传图片...',
          forbidClick: true
        })
        try {
          //? 2. 发送请求
          const { data } = await uploadAvator(blob)

          // console.log(data)
          //? 3. 更改父组件里的头像
          this.$emit('update-avator', data.data.photo)

          //? 4. 关闭弹层
          this.$parent.$parent.isShowAvator = false

          //? 提示成功
          this.$toast.success('图片上传成功!')
        } catch (error) {
          this.$toast.fail('图片上传失败!')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avator {
  height: 100%;
  position: relative;

  .img {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    width: 100%;
    height: 55%;
  }

  .toolbar {
    position: fixed;
    bottom: 0.13333rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 0.37333rem;
    color: #fff;
    padding: 0 0.2rem;
    box-sizing: border-box;
  }
}
</style>
